import { ref, onUnmounted } from 'vue'

function index(initCount = 60) {
    const timeCount = ref(0)
    const timer = ref()

    const startTime = () => {
        endTime()
        timeCount.value = initCount
        timer.value = setInterval(() => {
            timeCount.value -= 1
            if (timeCount.value <= 0) {
                endTime()
            }
        }, 1000)
    }

    const endTime = () => {
        if (timer.value) {
            clearInterval(timer.value)
            timer.value = null
        }
    }

    onUnmounted(() => {
        endTime()
    })

    return { timeCount, startTime, endTime }
}

export default index
